<?php
/**
 *
 *
 */
namespace Yz\modules\Generic;

class Controller_Entry
    extends Controller_AbstractFetch
{

    const ERROR_INVALID_ARGUMENT = ':InvalidArgument';


    /** The list of required arguments for controller
     *  @var array
     */
    protected $arguments = array(
        'itemId',
    );

    protected $model;
    protected $item;
    protected $itemId;
    protected $error;


    /****************************
     *      Public methods      *
     ****************************/

    /** Custom error handler for entry
     *      Handles item-not-found and invalid-number-of-args
     *
     *  @return this|false
     */
    public function doError( \Yz_Exception $ex )
    {
        if ($ex instanceof \Yz_Controller_Exception_InvalidArgument) {
            $t = $this->selectTemplate('Error');
            $t->errorMessage = $this->getErrorMessage() . self::ERROR_INVALID_ARGUMENT;
            return $this->outputTemplate($t);
        }
        if ($ex instanceof \Yz_Exception_ItemNotFound) {
            $t = $this->selectTemplate('Error');
            $t->errorMessage = $this->getErrorMessage() . self::ERROR_ITEM_NOT_FOUND;
            $t->itemId = $this->itemId;
            return $this->outputTemplate($t);
        }
        return false;
    }



    /** parse arguments: obtain itemId
     *  @param string(int) arg (from URI)
     *  @return this
     *  @throw Yz_Controller_Exception_InvalidArgument
     */
    protected function setItemId($arg)
    {
        $this->itemId = \Yz_Int::testPositive($arg);
        return $this;
    }


    /**
     *
     */
    protected function fetchData()
    {
        debug();
        $model = $this->selectModel();
        $this->item = $model->fetchItemById($this->itemId);
        return $this;
    }



    /**
     *  @return this
     *
     */
    protected function assignTemplateParams(\Yz_Template_Interface $t)
    {
        $t->item = $this->item;
        $t->itemId = $this->itemId;
        return $this ;
    }



}
